package br.com.passeionaweb.android.TabelaFipe;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;

import android.content.Context;

public class CacheManager {
	private static long OLD_THRESHOLD;

	static {
		Calendar cal = Calendar.getInstance();
		cal.roll(Calendar.DAY_OF_YEAR, -15);
		OLD_THRESHOLD = cal.getTimeInMillis();
	}

	private static String MAKES_FILE = "makes.json";

	private File cache;

	public CacheManager(Context context) {
		cache = context.getCacheDir();
	}

	public boolean isMakesfileOld() throws IOException {
		File makes = getMakesFile();
		if (makes.length() > 0) {
			Calendar now = Calendar.getInstance();
			return OLD_THRESHOLD < now.getTimeInMillis() - makes.lastModified();
		} else {
			return true;
		}
	}

	public boolean isModelsFileOld(String make) throws IOException {
		File models = getModelsFile(make);
		if (models.length() > 0) {
			Calendar now = Calendar.getInstance();
			return OLD_THRESHOLD < now.getTimeInMillis() - models.lastModified();
		} else {
			return true;
		}
	}

	public boolean saveModelsJSON(String make, String models) {
		try {
			File modelsfile = getModelsFile(make);
			FileOutputStream fileout = new FileOutputStream(modelsfile);
			fileout.write(models.getBytes());
			return true;
		} catch (IOException e) {
			return false;
		}
	}

	public boolean saveMakesJSON(String makes) {
		try {
			File makesfile = getMakesFile();
			FileOutputStream fileout = new FileOutputStream(makesfile);
			fileout.write(makes.getBytes());
			return true;
		} catch (IOException e) {
			return false;
		}
	}

	public String getModelsJSON(String make) throws IOException {
		File models = getModelsFile(make);
		return getStringFromInputStream(new FileInputStream(models));
	}

	public String getMakesJSON() throws IOException {
		File makes = getMakesFile();
		return getStringFromInputStream(new FileInputStream(makes));
	}

	public File getModelsFile(String make) throws IOException {
		File models = new File(cache, make + ".json");
		if (!models.exists()) {
			models.createNewFile();
		}
		return models;
	}

	public File getMakesFile() throws IOException {
		File makes = new File(cache, MAKES_FILE);
		if (!makes.exists()) {
			makes.createNewFile();
		}
		return makes;
	}

	private String getStringFromInputStream(InputStream is) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		String line = reader.readLine();
		StringBuilder builder = new StringBuilder();
		while (line != null) {
			builder.append(line);
			line = reader.readLine();
		}
		return builder.toString();
	}

}
